package edu.calpoly.android.echoes;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.AdapterView.OnItemLongClickListener;
import edu.calpoly.android.echoes.SaveView.OnSaveChangeListener;

public class SaveCursorAdapter extends CursorAdapter implements OnItemLongClickListener {

	/**
	 * The ID of the currently selected SaveView.
	 */
	private long m_nSelectedID;
	
	private SaveView m_sv;

	/**
	 * The OnJokeChangeListener that should be connected to each of the
	 * JokeViews created/managed by this Adapter.
	 */
	private OnSaveChangeListener m_listener;

	/**
	 * Parameterized constructor that takes in the application Context in which
	 * it is being used and the Collection of Joke objects to which it is bound.
	 * m_nSelectedPosition will be initialized to Adapter.NO_SELECTION.
	 * 
	 * @param context
	 *            The application Context in which this JokeListAdapter is being
	 *            used.
	 * 
	 * @param jokeCursor
	 *            A Database Cursor containing a result set of Jokes which
	 *            should be bound to JokeViews.
	 */
	public SaveCursorAdapter(Context context, Cursor jokeCursor) {
		super(context, jokeCursor);
		
		m_nSelectedID = Adapter.NO_SELECTION;
		m_listener = null;
	}

	/**
	 * Accessor method for retrieving the position in the dataset of the
	 * currently selected SaveView.
	 * 
	 * @return an integer representing the position in the dataset of the
	 *         currently selected SaveView.
	 */
	public long getSelectedID() {
		return m_nSelectedID;
	}
	
	public String getSelectedName() {
		return m_sv.getSave();
	}

	/**
	 * @param listener
	 *            The OnJokeChangeListener that will be notified when the
	 *            internal state of any Joke contained in one of this Adapters
	 *            JokeViews is changed.
	 */
	public void setOnSaveChangeListener(OnSaveChangeListener mListener) {
		m_listener = mListener;
	}


	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO
		m_nSelectedID = id;
		return false;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		String saveDB = ShapeDBAdapter.getSaveFromCursor(cursor);
		m_sv = (SaveView)view;
		
		m_sv.setSave(saveDB);
		m_sv.setOnSaveChangeListener(m_listener);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		String saveDB = ShapeDBAdapter.getSaveFromCursor(cursor);
		
		SaveView sv = new SaveView(context, saveDB);
		sv.setOnSaveChangeListener(m_listener);
		
		return sv;
	}
}
